<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" />
    <button>提交</button>
    <script>
      const btn = document.querySelector('button');
      btn.addEventListener('click', debounce(submit, 2000, true));
      function submit(e) {
        // console.log(e);
        // console.log(e.target);
        console.log(1);
      }

      //通过设置triggleNow的值为true 第一次点击的时候，立即执行
      // 为false时为普通防抖函数，第一次点击也需要等待三秒后执行
      function debounce(fn, time, triggleNow) {
        let timer = null;
        return function () {
          if (timer) clearTimeout(timer);
          if (triggleNow) {
            // console.log(!timer);
            let firstClick = !timer;
            if (firstClick) {
              fn.apply(this, arguments);
            }
            timer = setTimeout(() => {
              timer = null;
            }, time);
          } else {
            timer = setTimeout(() => {
              fn.apply(this, arguments);
              timer = null;
            }, time);
          }
        };
      }
    </script>
  </body>
</html>
